#define	i2c_wait_tip				\
		li	v0, LS2H_I2C_SR;	\
1:						\	
		lb	v1, 0x0(v0);		\
		andi	v1, v1, SR_TIP;		\
		bnez	v1, 1b;			\
		nop	

#define	i2c_wait_ack				\
		li	v0, LS2H_I2C_SR;	\
1:						\	
		lb	v1, 0x0(v0);		\
		and	v1, v1, SR_RXACK;	\
		bnez	v1, 1b;			\
		nop	

LEAF(i2cread)
/*
 * use register:
 *	v0, v1
 *	a0, a1
 *	input: a0,a1
 *	   a0: device ID
 *	   a1: register offset
 *	   v0: return value
 *
 */

/*i2c_send_b*/				
	/* load device address */
	andi	v1, a0, 0xfe		
	li	v0, LS2H_I2C_TXR	
	sb	v1, 0x0(v0)		

	/* send start frame */
	li	v1, CR_START | CR_WR	
	li	v0, LS2H_I2C_CR		
	sb	v1, 0x0(v0)		

	/* waite send finished */
//	i2c_wait_tip			
	li	v0, LS2H_I2C_SR;	
1:						
	lb	v1, 0x0(v0);		
	andi	v1, v1, SR_TIP;		
	bnez	v1, 1b;			
	nop	
	
	/* load data to be send */
	move	v1, a1			
	li	v0, LS2H_I2C_TXR	
	sb	v1, 0x0(v0)		

	/* send data frame */
	li	v1, CR_WR		
	li	v0, LS2H_I2C_CR		
	sb	v1, 0x0(v0)		

	/* waite send finished */
//	i2c_wait_tip			
	li	v0, LS2H_I2C_SR;	
1:						
	lb	v1, 0x0(v0);		
	andi	v1, v1, SR_TIP;		
	bnez	v1, 1b;			
	nop	

/* i2c_read_b */			       
	/* load device address */
	ori	v1, a0, 0x1
	li	v0, LS2H_I2C_TXR	
	sb	v1, 0x0(v0)		
	
	/* send start frame */
	li	v1, CR_START | CR_WR	
	li	v0, LS2H_I2C_CR		
	sb	v1, 0x0(v0)		

	/* waite send finished */
//	i2c_wait_tip			
	li	v0, LS2H_I2C_SR;	
1:						
	lb	v1, 0x0(v0);		
	andi	v1, v1, SR_TIP;		
	bnez	v1, 1b;			
	nop	
	
	/* receive data to fifo */
	li	v1, CR_RD | CR_ACK	
	li	v0, LS2H_I2C_CR		
	sb	v1, 0x0(v0)		

//	i2c_wait_tip			
	li	v0, LS2H_I2C_SR;	
1:						
	lb	v1, 0x0(v0);		
	andi	v1, v1, SR_TIP;		
	bnez	v1, 1b;			
	nop	

	/* read data from fifo */
	li	v0, LS2H_I2C_RXR	
	lb	a1, 0x0(v0)

/* i2c_stop */				
	/* free i2c bus */
	li	v0, LS2H_I2C_CR		
	li	v1, CR_STOP		
	sb	v1, 0x0(v0)		
1:					
	li	v0, LS2H_I2C_SR		
	lb	v1, 0x0(v0)		
	andi	v1, v1, SR_BUSY		
	bnez	v1, 1b			
	nop				
	
	move	v0, a1

	jr	ra
	nop
END(i2cread)
